package com.jrx.anytxn.transaction.job.coupon.step;

import com.alibaba.fastjson.JSON;
import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.service.ICustomerRightService;
import com.jrx.anytxn.customer.service.ITlCouponDetailService;
import com.jrx.anytxn.param.entity.PrActivityInfo;
import com.jrx.anytxn.param.entity.PrRightsAndInterests;
import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import com.jrx.anytxn.redisson.service.RedissonLockService;
import com.jrx.anytxn.redisson.util.LockType;
import com.jrx.anytxn.transaction.config.CouponConfig;
import com.jrx.anytxn.transaction.job.coupon.dto.CustomerRightsDTO;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONArray;
import org.redisson.api.RLock;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName CompensationActivateWriter
 *
 * @author lujianyou zebin.zhang
 * @version 1.0
 * @description 补偿激活时未送120元优惠批处理 - Writer
 * @date 2022/02/11 16:56
 **/
@Service
@Slf4j
public class CompensationActivateWriter implements ItemWriter<CustomerRightsDTO> {
    private static final String COUPON_LOCK_TEMPLATE = "COUPON_COMPENSATION_ACTIVATE_BATCH";
    @Autowired
    private ICustomerRightService customerRightService;
    @Autowired
    private ITlCouponDetailService tlCouponDetailService;
    @Autowired
    private IPrActivityInfoService activityInfoService;
    @Autowired
    private IPrRightsAndInterestsService rightsAndInterestsService;
    @Autowired
    private RedissonLockService redissonLockService;

    @Override
    public void write(List<? extends CustomerRightsDTO> items) throws Exception {
        log.info("access into CompensationActivateWriter->write()");
        RLock rlock = redissonLockService.getRLock(COUPON_LOCK_TEMPLATE, LockType.REENTRANT_LOCK);
        try {
            rlock.tryLock(15,15, TimeUnit.SECONDS);
            if(items.isEmpty()){
                return;
            }

            for (int i = 0; i < items.size(); i++) {
                CustomerRightsDTO item  = items.get(i);
                List<CmCustomerRightInfo> cmCustomerRightInfoList = item.getCmCustomerRightInfoList();
                List<TlCouponDetail> tlCouponDetailList = item.getTlCouponDetailList();
                LinkedHashSet<String> rightsLinkedHashSet = item.getRightsLinkedHashSet();
                Map<String, Integer> rightsMap = item.getRightsMap();
                Map<String, PrRightsAndInterests> rightsInfoMap = item.getRightsInfoMap();
                log.info("---校验、扣减活动库存---");
                CmCustomerRightInfo cmCustomerRightInfo = cmCustomerRightInfoList.get(0);
                String activityId = null;
                if (null != cmCustomerRightInfo){
                    activityId = cmCustomerRightInfo.getActivityId();//同一个客户获得的权益来自同一个活动
                }else{
                    log.info("未获取到客户权益信息，补发终止！");
                    continue;
                }
                PrActivityInfo activityInfo = activityInfoService.getByTenantIdAndActivityId(Constants.DEFAULT_TENANT_ID, activityId);
                if (activityInfo.getStoreQuantity() < 1) {
                    throw new TxnBizException(TxnRespCode.ACTIVITY_STOCK_DEFICIENT);
                }else{
                    activityInfo.setStoreQuantity(activityInfo.getStoreQuantity() - 1);
                    activityInfo.setUpdateTime(new Date());
                    activityInfo.setUpdateBy("batch");
                    activityInfoService.updateByPrimaryKeySelective(activityInfo);
                }
                log.info("---校验、扣减权益库存---");
                for (int j = 0; j < rightsLinkedHashSet.size(); j++) {
                    String rightsId = (String) rightsLinkedHashSet.toArray()[j];
                    Integer count = rightsMap.get(rightsId);
                    PrRightsAndInterests prRightsAndInterests = rightsInfoMap.get(rightsId);
                    if (prRightsAndInterests.getStoreQuantity() < count) {
                        throw new TxnBizException(TxnRespCode.RIGHTS_AND_INTEREST_STOCK_DEFICIENT);
                    }else{
                        prRightsAndInterests.setStoreQuantity(prRightsAndInterests.getStoreQuantity()-count);
                        prRightsAndInterests.setUpdateBy("batch");
                        prRightsAndInterests.setUpdateTime(new Date());
                        rightsAndInterestsService.update(prRightsAndInterests);
                    }
                }
                log.info("---发放客户权益---");
                log.info(String.valueOf(cmCustomerRightInfoList));
                customerRightService.insertBatch(cmCustomerRightInfoList);
                tlCouponDetailService.insertBatch(tlCouponDetailList);
            }
        }finally {
            if(rlock.isLocked() && rlock.isHeldByCurrentThread()){
                rlock.unlock();
            }
        }

    }
}
